import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:liuxlcommon/view/loading_view.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

typedef RefreshCallback = Function();

///统一 加载中，加载完成，等
class CahtLoadingView extends StatefulWidget {
  static Color? textColor;

  ///内容 可不传，itemCall 跟 body 不可同时为空
  BodyCall? body;

  /// 当 body为空的时候，默认是个是个listview，的中 itemCall。
  ItemCall? itemCall;
  ScrollController? scrollController;

  /// datas 数据
  dynamic? datas;
  loadCallback11? future;

  ///下拉
  bool? isPullDown = false;

  ///上拉
  bool? isPullUp = false;

  ///瀑布流
  bool isStaggered = false;

  ///网络请求 放里面，不然不能判断是否在加载中。
  ///type : 0 初始化加载，1 下拉，2 上拉。
  loadCallback? onLoad;
  RefreshCallback? onSuccess;
  ValueChanged<LoadState>? onStateClick;

  ///状态
  LoadState loadState = LoadState.LOADINT;
  double? childAspectRatio;
  int? crossAxisCount = 0;
  Widget? emptyView;
  Widget? errorView;
  int? initialScrollIndex;
  int pageSize;

  static Widget defaultEmptyView = Center(
    child: Image.asset('assets/images/empty.png'),
  );
  static Widget defaultErrorView = Center(
    child: Image.asset('assets/images/error.png'),
  );

  CahtLoadingView(
      {super.key,
      this.body,
      required this.datas,
      this.itemCall,
      this.onLoad,
      this.onStateClick,
      this.onSuccess,
      this.isPullUp = true,
      this.isPullDown = true,
      this.crossAxisCount,
      this.childAspectRatio,
      this.scrollController,
      this.pageSize = 10,
      this.future,
      this.emptyView,
      this.initialScrollIndex,
      this.errorView}) {
    if (emptyView == null) emptyView = defaultEmptyView;
    if (errorView == null) errorView = defaultErrorView;
    if (datas != null) loadState = LoadState.SUCCESS; //首页切换回重新执行。 防止重复执行。
    if (datas != null && datas is List && datas.length == 0) {
      loadState = LoadState.EMPTY;
    }
    if (body != null) {
      loadState = LoadState.SUCCESS;
    }
  }

  @override
  State<StatefulWidget> createState() => childCahtLoadingView();
}

class childCahtLoadingView extends State<CahtLoadingView> {
  bool isPullUpLoading = false;
  bool isFuture = false;
  final RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  updateUI({datas}) {
    widget.datas = datas;
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.body == null) {
      return view();
    }
    if (widget.datas != null && widget.body != null) {
      widget.future = null;
    }
    if (widget.future != null && !isFuture) {
      widget.loadState = LoadState.LOADINT;
      widget.future!().then((value) async {
        if (value == null)
          widget.loadState = LoadState.ERROR;
        else
          widget.loadState = LoadState.SUCCESS;
        isFuture = true;
        setState(() {});

        if (widget.onSuccess != null) {
          widget.onSuccess!();
        } else {}
      });
    }
    return view1(null);
  }

  Widget view() {
    int count = widget.datas == null ? 0 : widget.datas.length;
    // if(widget.isPullUp!)count++;
    return view1(SmartRefresher(
      enablePullDown: widget.isPullDown ?? false,
      enablePullUp: widget.isPullUp ?? false,
      header: const MaterialClassicHeader(),
      footer: CustomFooter(
        loadStyle: LoadStyle.ShowWhenLoading,
        builder: (BuildContext context, LoadStatus? mode) {
          Widget body;
          if (mode == LoadStatus.idle) {
            body = Text(
              "上拉加载",
              style: TextStyle(
                  fontSize: 12,
                  color: CahtLoadingView.textColor ?? Colors.white),
            );
          } else if (mode == LoadStatus.loading) {
            body = const CupertinoActivityIndicator();
          } else if (mode == LoadStatus.failed) {
            body = Text("加载失败！点击重试！",
                style: TextStyle(
                    fontSize: 12,
                    color: CahtLoadingView.textColor ?? Colors.white));
          } else if (mode == LoadStatus.canLoading) {
            body = Text("松手,加载更多!",
                style: TextStyle(
                    fontSize: 12,
                    color: CahtLoadingView.textColor ?? Colors.white));
          } else {
            body = Text("没有更多数据了!",
                style: TextStyle(
                    fontSize: 12,
                    color: CahtLoadingView.textColor ?? Colors.white));
          }
          return SizedBox(
            height: 55.0,
            child: Center(child: body),
          );
        },
      ),
      controller: _refreshController,
      onRefresh: () async {
        List lists = await widget.onLoad!(1);
        setState(() {});
        if (widget.onSuccess != null) {
          widget.onSuccess!();
        }
        _refreshController.refreshCompleted();
      },
      onLoading: () {
        widget.onLoad!(2).then((value) {
          isPullUpLoading = false; //加载完成
          setState(() {});
          _refreshController.loadComplete();
        });
      },
      child: (widget.crossAxisCount ?? 0) == 0
          ? ListView.builder(
              controller: widget.scrollController,
              padding: EdgeInsets.zero,
              physics: const AlwaysScrollableScrollPhysics(),
              itemCount: count,
              itemBuilder: (context, position) {
                return itemView(position);
              })
          : GridView.builder(
              padding: EdgeInsets.zero,
              itemCount: count,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: widget.crossAxisCount ?? 1, //横轴元素个数
                  childAspectRatio: widget.childAspectRatio ?? 105 / 156),
              //子组件宽高长度比例
              itemBuilder: (BuildContext context, int index) {
                return itemView(index);
              }),
    ));
  }

  itemView(position) {
    print("ListView position:" + position.toString());
    return widget.itemCall!(context, position);
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void didUpdateWidget(covariant CahtLoadingView oldWidget) {
    super.didUpdateWidget(oldWidget);
    isFuture = false;

    ///外面刷新 。取消限制。
  }

  //是否加载中。 加载的时候不响应其他 网络请求
  bool isLoading = false;

  Widget view1(body1) {
    Widget? body = body1;
    if (widget.loadState == LoadState.SUCCESS) {
      return body ?? widget.body!();
    } else if (widget.loadState == LoadState.LOADINT) {
      if (widget.onLoad != null) {
        //加载中
        if (widget.loadState == LoadState.ERROR) {
          return const SizedBox(
            width: 0,
          );
        }
        widget.loadState = LoadState.LOADINT;
        isPullUpLoading = true;
        Future future = widget.onLoad!(0);
        future.then((datas) {
          isPullUpLoading = false;
          if (widget.body != null) {
            if (widget.datas == null && datas == null) {
              widget.loadState = LoadState.ERROR;
            } else {
              widget.loadState = LoadState.SUCCESS;
            }
          } else {
            //body 等于null 表示是个列表
            if (widget.datas == null && datas == null) {
              widget.loadState = LoadState.ERROR;
            } else if (datas.length == 0) {
              widget.loadState = LoadState.EMPTY;
            } else {
              widget.loadState = LoadState.SUCCESS;
            }
          }
          setState(() {});
          if (widget.onSuccess != null) {
            widget.onSuccess!();
          }
        });
      }
      return Center(child: CupertinoActivityIndicator());
    } else if (widget.loadState == LoadState.EMPTY)
      return InkWell(
        child: widget.emptyView ??
            Center(
              child: Image.asset('assets/images/empty.png'),
            ),
        onTap: () {
          if (widget.onStateClick != null) {
            widget.onStateClick!(widget.loadState);
          }
        },
      );
    else if (widget.loadState == LoadState.ERROR)
      return InkWell(
          child: widget.errorView ??
              Center(
                child: Image.asset('assets/images/error.png'),
              ),
          onTap: () {
            if (widget.onStateClick != null) {
              widget.onStateClick!(widget.loadState);
            }
          });
    return SizedBox(
      width: 0,
    );
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }
}

enum LoadState {
  ///加载中
  LOADINT,

  ///加载成功
  SUCCESS,

  ///加载失败
  ERROR,

  ///空
  EMPTY;
}
